package com.martin.study;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.Map;

@Component
public class SpringWithJdkPropertyEditorDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringWithJdkPropertyEditorDemo.class);
		UserService userService = context.getBean(UserService.class);
		userService.test();
	}

	@Bean
	public CustomEditorConfigurer customEditorConfigurer() {
		CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
		Map<Class<?>, Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>();

		// 表示StringToUserPropertyEditor可以将String转化成User类型，在Spring源码中，如果发现当前对象是String，而需要的类型是User，就会使用该PropertyEditor来做类型转化
		propertyEditorMap.put(JdkPropertyEditorDemo.User.class, JdkPropertyEditorDemo.class);
		customEditorConfigurer.setCustomEditors(propertyEditorMap);
		return customEditorConfigurer;
	}

	@Component
	public class UserService {

		@Value("孔子墨#男")
		private JdkPropertyEditorDemo.User user;

		public void test() {
			System.out.println(user);
		}

	}
}
